package com.wlyuan.open.domain.source.service.impl;

import com.alibaba.fastjson.JSON;
import com.wlyuan.core.domain.valueobj.TenantId;
import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.open.domain.source.assembler.RelationAssembler;
import com.wlyuan.open.domain.source.assembler.TenantAssembler;
import com.wlyuan.open.domain.source.service.IOpenTenantService;
import com.wlyuan.open.dto.OpenTenantSyncDTO;
import com.wlyuan.open.dto.tenant.OpenCompanyTenantSyncDTO;
import com.wlyuan.open.dto.tenant.OpenDriverTenantSyncDTO;
import com.wlyuan.open.dto.tenant.OpenTenantRelationSyncDTO;
import com.wlyuan.open.infrastructure.exception.SourceValueErrorException;
import com.wlyuan.tenant.api.ITenantService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

/**
 * @author yuanzheng
 */
@Service
@Slf4j
@RequiredArgsConstructor
@Data
public class OpenTenantServiceImpl implements IOpenTenantService {
    private static final TenantId ZERO_TENANT_ID = new TenantId(0L);
    @DubboReference(check = false)
    private ITenantService tenantService;

    @Override
    public Long sync(OpenTenantSyncDTO source) {
        if (source instanceof OpenCompanyTenantSyncDTO) {
            var dto = (OpenCompanyTenantSyncDTO) source;
            var creation = TenantAssembler.assemble(dto);
            logger.info("创建公司租户请求：{}", JSON.toJSON(creation));
            var tenant = tenantService.rewrite(creation);
            AssertUtils.assertNotNull(tenant, new SourceValueErrorException("创建公司租户失败"), source);
            return tenant.getTenantId();
        } else if (source instanceof OpenDriverTenantSyncDTO) {
            var dto = (OpenDriverTenantSyncDTO) source;
            var creation = TenantAssembler.assemble(dto);
            logger.info("创建个体司机租户请求：{}", JSON.toJSON(creation));
            var tenant = tenantService.rewrite(creation);
            AssertUtils.assertNotNull(tenant, new SourceValueErrorException("创建司机租户失败"), source);
            return tenant.getTenantId();
        } else if (source instanceof OpenTenantRelationSyncDTO) {
            //全量同步同步租户邀请关系，因为全量时需要找到新的邀请者租户ID和邀请者用户ID，所以全量同步时，单独同步租户邀请关系
            var dto = (OpenTenantRelationSyncDTO) source;
            var creation = RelationAssembler.assembler(dto);
            var tenant = tenantService.rewrite(creation);
            AssertUtils.assertNotNull(tenant, new SourceValueErrorException("租户邀请关系失败"), source);
            return tenant.getTenantId();
        }
        return null;
    }

}
